package com.fishingwithme.domain.settings;

import com.fishingwithme.infrastructure.dtos.AgrPpDto;
import com.fishingwithme.infrastructure.dtos.CreditLevelRuleDto;
import com.fishingwithme.infrastructure.dtos.CreditRuleDto;
import com.fishingwithme.infrastructure.dtos.FeedbackListDto;
import com.fishingwithme.infrastructure.dtos.SaveAgrRequest;
import com.fishingwithme.infrastructure.dtos.UpdateAgrRequest;
import com.fishingwithme.infrastructure.dtos.AgrVersionDto;
import com.fishingwithme.infrastructure.mapper.AgrPpMapper;
import com.fishingwithme.infrastructure.mapper.SettingsMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class SettingsServiceImpl implements SettingsService {

    @Autowired
    private SettingsMapper settingsMapper;
    
    @Autowired
    private AgrPpMapper agrPpMapper;

    @Override
    public List<CreditLevelRuleDto> getLevelRules() {
        return settingsMapper.selectAllLevelRules();
    }

    @Override
    public List<CreditRuleDto> getCreditRules() {
        return settingsMapper.selectAllCreditRules();
    }

    @Override
    public IPage<FeedbackListDto> getFeedbackList(int pageNum, int pageSize) {
        if (pageNum <= 0) {
            pageNum = 1;
        }
        if (pageSize <= 0 || pageSize > 100) {
            pageSize = 10;
        }
        
        Page<FeedbackListDto> page = new Page<>(pageNum, pageSize);
        return settingsMapper.selectFeedbackPage(page);
    }

    @Override
    public List<AgrPpDto> getAgr(String type) {
        return settingsMapper.selectAgrByType(type);
    }
    
    @Override
    public List<AgrVersionDto> getAgrVersionsByType(String type) {
        if (StringUtils.isBlank(type)) {
            return null;
        }
        
        // 创建查询条件
        QueryWrapper<AgrPp> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("type", type);
        queryWrapper.select("id", "ver", "enabled", "created_at");
        queryWrapper.orderByDesc("created_at");
        
        // 查询所有版本
        List<AgrPp> agrPpList = agrPpMapper.selectList(queryWrapper);
        
        // 转换为DTO列表
        return agrPpList.stream().map(agrPp -> {
            AgrVersionDto dto = new AgrVersionDto();
            dto.setId(agrPp.getId().toString());
            dto.setVer(agrPp.getVer());
            dto.setEnabled(agrPp.getEnabled() ? "1" : "0");
            dto.setCreatedAt(agrPp.getCreatedAt());
            return dto;
        }).collect(java.util.stream.Collectors.toList());
    }

    @Transactional
    @Override
    public AgrPpDto newVersion(Long id) {
        AgrPp existingAgrPp = agrPpMapper.selectById(id);
        if (existingAgrPp == null) {
            throw new RuntimeException("数据不存在.");
        }

        Integer version = getMaxVersionByType(existingAgrPp.getType());
        version++;

        AgrPp newAgrPp = new AgrPp();
        BeanUtils.copyProperties(existingAgrPp,newAgrPp);
        newAgrPp.setVer(version);
        newAgrPp.setId(null);
        newAgrPp.setEnabled(Boolean.FALSE);
        int cnt = agrPpMapper.insert(newAgrPp);
        if(cnt != 1 ) {
            throw new RuntimeException("添加版本失败.");
        }

        QueryWrapper<AgrPp> query = new QueryWrapper<>();
        query.eq("type", existingAgrPp.getType());
        query.eq("ver",version);
        AgrPp updatedApp = agrPpMapper.selectOne(query);
        AgrPpDto dto = new AgrPpDto();
        BeanUtils.copyProperties(updatedApp, dto);
        return dto;
    }

    @Override
    public AgrPpDto getAgrById(Long id) {
        AgrPp agrPp  = agrPpMapper.selectById(id);
        AgrPpDto dto = new AgrPpDto();
        BeanUtils.copyProperties(agrPp,dto);
        return dto;
    }

    @Override
    public Boolean enableAgr(Long id, Boolean enabled) {
        AgrPp agrPp  = agrPpMapper.selectById(id);
        if (agrPp == null) {
            return false;
        }
        
        // 如果是启用操作，需要先禁用该类型的其他版本
        if (Boolean.TRUE.equals(enabled)) {
            disableOtherVersions(agrPp.getType());
        }
        
        agrPp.setEnabled(enabled);
        agrPp.setUpdatedAt(new Date());
        return agrPpMapper.updateById(agrPp) > 0;
    }

    @Override
    public AgrPpDto getAgrByType(String type) {
        if (StringUtils.isBlank(type)) {
            return null;
        }
        
        AgrPp agrPp = agrPpMapper.selectByType(type);
        if (agrPp == null) {
            return null;
        }
        
        AgrPpDto dto = new AgrPpDto();
        BeanUtils.copyProperties(agrPp, dto);
        return dto;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveAgr(SaveAgrRequest request) {
        // 参数校验
        if (request == null || request.getType() == null || StringUtils.isBlank(request.getContent())) {
            return false;
        }

        
        // 创建实体
        AgrPp agrPp = new AgrPp();
        BeanUtils.copyProperties(request, agrPp);
        agrPp.setEnabled(false);
        agrPp.setCreatedAt(new Date());
        agrPp.setUpdatedAt(new Date());
        
        // 计算新版本号：基于同类型现有最大版本号加1
        Integer maxVersion = getMaxVersionByType(request.getType());
        agrPp.setVer(maxVersion + 1);
        
        return agrPpMapper.insert(agrPp) > 0;
    }
    
    /**
     * 获取指定类型协议的最大版本号
     */
    private Integer getMaxVersionByType(String type) {
        if (StringUtils.isBlank(type)) {
            return 0;
        }
        
        // 查询同类型的所有协议
        QueryWrapper<AgrPp> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("type", type);
        queryWrapper.select("ver");
        queryWrapper.orderByDesc("ver");
        
        // 只查询一条记录，获取最大版本号
        queryWrapper.last("LIMIT 1");
        
        List<AgrPp> agrPps = agrPpMapper.selectList(queryWrapper);
        if (agrPps == null || agrPps.isEmpty()) {
            return 0;
        }
        
        // 返回最大版本号
        return agrPps.get(0).getVer();
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateAgr(UpdateAgrRequest request) {
        // 参数校验
        if (request == null || request.getId() == null ||  StringUtils.isBlank(request.getContent())) {
            return false;
        }
        
        // 检查记录是否存在
        AgrPp existingAgrPp = agrPpMapper.selectById(Long.valueOf(request.getId()));
        if (existingAgrPp == null) {
            return false;
        }
        
        // 更新实体
        BeanUtils.copyProperties(request, existingAgrPp);
        existingAgrPp.setUpdatedAt(new Date());
        
        return agrPpMapper.updateById(existingAgrPp) > 0;
    }
    
    /**
     * 禁用指定类型的所有其他版本
     */
    private void disableOtherVersions(String type) {
        QueryWrapper<AgrPp> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("type", type);
        queryWrapper.eq("enabled", Boolean.TRUE);
        
        List<AgrPp> existingEnabledAgrPps = agrPpMapper.selectList(queryWrapper);
        for (AgrPp agrPp : existingEnabledAgrPps) {
            agrPp.setEnabled(false);
            agrPp.setUpdatedAt(new Date());
            agrPpMapper.updateById(agrPp);
        }
    }
    
    @Override
    public IPage<AgrPpDto> listAgrs(int pageNum, int pageSize, String type, Boolean enabled) {
        // 参数校验和默认值处理
        if (pageNum <= 0) {
            pageNum = 1;
        }
        if (pageSize <= 0 || pageSize > 100) {
            pageSize = 10;
        }
        
        // 创建分页对象
        Page<AgrPp> page = new Page<>(pageNum, pageSize);
        
        // 查询所有协议数据，先按enabled字段排序（启用状态排在前面），再按创建时间倒序排序
        QueryWrapper<AgrPp> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("enabled").orderByDesc("created_at");
        
        // 添加type过滤条件（如果type不为空）
        if (StringUtils.isNotBlank(type)) {
            queryWrapper.eq("type", type);
        }
        
        // 添加enabled过滤条件（如果enabled不为null）
        if (enabled != null) {
            queryWrapper.eq("enabled", enabled);
        }
        
        // 执行分页查询
        Page<AgrPp> agrPpPage = agrPpMapper.selectPage(page, queryWrapper);
        
        // 转换为DTO对象的分页结果
        return agrPpPage.convert(agrPp -> {
            AgrPpDto dto = new AgrPpDto();
            BeanUtils.copyProperties(agrPp, dto);
            
            // 手动处理父类AuditInfo中的属性，解决类型不匹配问题
            if (agrPp.getCreatedAt() != null) {
                dto.setCreatedAt(agrPp.getCreatedAt());
            }
            if (agrPp.getUpdatedAt() != null) {
                dto.setUpdatedAt(agrPp.getUpdatedAt());
            }
            if (agrPp.getCreatedBy() != null) {
                dto.setCreatedBy(agrPp.getCreatedBy());
            }
            if (agrPp.getUpdatedBy() != null) {
                dto.setUpdatedBy(agrPp.getUpdatedBy());
            }
            dto.setId(agrPp.getId());
            
            return dto;
        });
    }
}